package com.nutrition.health.controller;

import com.nutrition.health.model.User;
import com.nutrition.health.model.UserHealthProfile;
import com.nutrition.health.service.UserService;
import com.nutrition.health.service.UserHealthProfileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 用户控制器
 * 处理用户注册、登录和健康档案管理
 */
@RestController
@RequestMapping("/users")
@Api(tags = "用户管理", description = "用户注册、登录和健康档案管理")
public class UserController {

    private final UserService userService;
    private final UserHealthProfileService userHealthProfileService;

    @Autowired
    public UserController(UserService userService, UserHealthProfileService userHealthProfileService) {
        this.userService = userService;
        this.userHealthProfileService = userHealthProfileService;
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @return 注册结果
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "创建新用户账号")
    public ResponseEntity<User> registerUser(
            @ApiParam(value = "用户信息", required = true) @Valid @RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.existsByUsername(user.getUsername())) {
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }

        // 创建新用户
        User createdUser = userService.createUser(user);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
    }

    /**
     * 用户登录
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "验证用户凭据并返回登录结果")
    public ResponseEntity<Map<String, Object>> loginUser(
            @ApiParam(value = "登录请求", required = true) @RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        // 验证用户凭据
        Optional<User> userOpt = userService.getUserByUsername(username);
        if (userOpt.get() == null || !userService.validatePassword(password, userOpt.get().getPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        User user = userOpt.get();

        // 返回用户信息和令牌（在实际应用中应使用JWT或其他认证机制）
        Map<String, Object> response = new HashMap<>();
        response.put("user", user);
        response.put("token", "mock-jwt-token"); // 模拟令牌

        return ResponseEntity.ok(response);
    }

    /**
     * 获取用户信息
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户详细信息")
    public ResponseEntity<User> getUserById(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        return userService.getUserById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 更新用户信息
     * @param id 用户ID
     * @param user 更新的用户信息
     * @return 更新后的用户信息
     */
    @PutMapping("/{id}")
    @ApiOperation(value = "更新用户信息", notes = "根据用户ID更新用户信息")
    public ResponseEntity<User> updateUser(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long id,
            @ApiParam(value = "更新的用户信息", required = true) @Valid @RequestBody User user) {
        return userService.getUserById(id)
                .map(existingUser -> {
                    user.setId(id);
                    User updatedUser = userService.updateUser(id, user);
                    return ResponseEntity.ok(updatedUser);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    // 健康档案相关方法已移至UserHealthProfileController

    /**
     * 计算用户的BMI指数
     * @param userId 用户ID
     * @return BMI计算结果
     */
    @GetMapping("/{userId}/bmi")
    @ApiOperation(value = "计算用户BMI", notes = "根据用户健康档案计算BMI指数")
    public ResponseEntity<Map<String, Object>> calculateBMI(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        return userHealthProfileService.getProfileByUserId(userId)
                .map(profile -> {
                    // 计算BMI
                    double heightInMeters = profile.getHeight() / 100.0;
                    double bmi = profile.getWeight() / (heightInMeters * heightInMeters);

                    // 确定BMI状态
                    String status;
                    if (bmi < 18.5) {
                        status = "体重过轻";
                    } else if (bmi < 24) {
                        status = "正常范围";
                    } else if (bmi < 28) {
                        status = "超重";
                    } else {
                        status = "肥胖";
                    }

                    // 构建响应
                    Map<String, Object> result = new HashMap<>();
                    result.put("bmi", Math.round(bmi * 10) / 10.0); // 保留一位小数
                    result.put("status", status);

                    return ResponseEntity.ok(result);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 计算用户的基础代谢率(BMR)
     * @param userId 用户ID
     * @return BMR计算结果
     */
    @GetMapping("/{userId}/bmr")
    @ApiOperation(value = "计算用户基础代谢率", notes = "根据用户健康档案计算基础代谢率")
    public ResponseEntity<Map<String, Object>> calculateBMR(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        double bmr = userHealthProfileService.calculateBMR(userId);
        if (bmr <= 0) {
            return ResponseEntity.notFound().build();
        }

        double tdee = userHealthProfileService.calculateDailyCalorieNeeds(userId);

        // 构建响应
        Map<String, Object> result = new HashMap<>();
        result.put("bmr", Math.round(bmr));
        result.put("tdee", Math.round(tdee));

        // 获取健康档案以确定目标
        Optional<UserHealthProfile> profileOpt = userHealthProfileService.getProfileByUserId(userId);
        if (profileOpt.isPresent()) {
            UserHealthProfile profile = profileOpt.get();

            // 根据目标调整卡路里
            switch (profile.getGoal()) {
                case LOSE_WEIGHT:
                    result.put("targetCalories", Math.round(tdee * 0.85)); // 减少15%
                    break;
                case GAIN_WEIGHT:
                case BUILD_MUSCLE:
                    result.put("targetCalories", Math.round(tdee * 1.15)); // 增加15%
                    break;
                default:
                    result.put("targetCalories", Math.round(tdee)); // 维持
            }
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户的营养需求
     * @param userId 用户ID
     * @return 营养需求计算结果
     */
    @GetMapping("/{userId}/nutrition-needs")
    @ApiOperation(value = "获取用户营养需求", notes = "根据用户健康档案计算每日营养需求")
    public ResponseEntity<Map<String, Object>> getNutritionNeeds(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        Map<String, Double> nutrientRequirements = userHealthProfileService.generateNutrientRequirements(userId);
        if (nutrientRequirements.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        Map<String, Object> result = new HashMap<>(nutrientRequirements);

        return ResponseEntity.ok(result);
    }

    /**
     * 初始化测试数据
     * @return 初始化结果
     */
    @PostMapping("/init-test-data")
    @ApiOperation(value = "初始化测试数据", notes = "创建测试用户和健康档案")
    public ResponseEntity<Map<String, Object>> initTestData() {
        try {
            // 创建测试用户
            User testUser = new User();
            testUser.setUsername("testuser");
            testUser.setPassword("password123");
            testUser.setFullName("测试用户");
            testUser.setEmail("test@example.com");
            testUser.setPhone("13800138000");

            // 检查用户名是否已存在
            if (userService.existsByUsername(testUser.getUsername())) {
                // 如果已存在，返回该用户
                User existingUser = userService.getUserByUsername(testUser.getUsername()).get();

                Map<String, Object> result = new HashMap<>();
                result.put("message", "测试用户已存在");
                result.put("userId", existingUser.getId());

                // 检查是否有健康档案
                Optional<UserHealthProfile> profileOpt = userHealthProfileService.getProfileByUserId(existingUser.getId());
                result.put("hasHealthProfile", profileOpt.isPresent());

                return ResponseEntity.ok(result);
            }

            // 创建新用户
            User createdUser = userService.createUser(testUser);

            // 创建健康档案
            UserHealthProfile profile = new UserHealthProfile();
            profile.setUserId(createdUser.getId());
            profile.setDateOfBirth(LocalDate.of(1990, 1, 1));
            profile.setGender(UserHealthProfile.Gender.MALE);
            profile.setHeight(175.0);
            profile.setWeight(70.0);
            profile.setTargetWeight(68.0);
            profile.setActivityLevel(UserHealthProfile.ActivityLevel.MODERATELY_ACTIVE);
            profile.setGoal(UserHealthProfile.Goal.LOSE_WEIGHT);

            UserHealthProfile createdProfile = userHealthProfileService.createProfile(createdUser.getId(), profile);

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("message", "测试数据初始化成功");
            result.put("userId", createdUser.getId());
            result.put("profileId", createdProfile.getId());

            return ResponseEntity.status(HttpStatus.CREATED).body(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "初始化测试数据失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
}